<template>
  <div class="customer">
    <el-form :model="form" style="background-color: #FFFFFF;padding: 20px 0;">
      <!--                 <el-form-item label="系列名称：" label-width="150px">
                    <el-input auto-complete="off"  v-model="form.name" style="width: 40%;"></el-input>
                </el-form-item>
                <el-form-item label="上传大图：" label-width="150px">
                    <we-ui-uploads :images="form.image"
                                   :maxCount="1"
                                   :maxSize="1024*1024"
                                   @uploading="uploading" ></we-ui-uploads>
                </el-form-item> -->
      <el-form-item label="选择商品：" label-width="150px">
        <el-button size="small" type="primary" @click="fetchGoods(1);dialogTableVisible=true">点击选择
        </el-button>
      </el-form-item>
    </el-form>
    <el-table :data="pageInfo2.rows" style="margin-bottom: 20px;">
      <el-table-column label="排序值" width="110">
        <template scope="scope">
          <!-- <el-input  v-model="scope.row.sort_value" style="width: 80px;" @blur="editOrder(scope.row,$event)" @focus="setOldProbability(scope.row,scope.row.sort_value)"></el-input> -->
          <el-button @click="setOldProbability(scope.row,scope.row.sort_value);showDilog(scope.row)">{{ scope.row.sort_value }}</el-button>
        </template>
      </el-table-column>
      <el-table-column width="300" label="商品名称">
          <template scope="scope">
            <div style="display: inline-block;">
              <img class="banner" :src="scope.row.goodCover" style="width:120px;" >
                    </div>
              <div style="display: inline-block;width: 120px;vertical-align: middle;padding: 10px;">{{scope.row.goodName}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="good_Price" label="价格（元）">
          <template scope="scope">
            <span>{{ scope.row.goodPrice }}</span>
          </template>
        </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button @click.native.prevent="deleteRow(scope.$index,scope.row.goodId)" type="danger" size="small">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="paginate">
      <el-pagination @current-change="handleCurrentChange2" :current-page="pageInfo2.pageNum" :page-size="pageInfo2.pageSize" layout="total, prev, pager, next, jumper" :total="pageInfo2.count">
      </el-pagination>
    </div>
    </el-row>
    <div style="margin-left: 30px;margin-bottom: 20px;">
      <el-button type="primary" @click="submit()" :loading="loading">保 存
      </el-button>
    </div>
    <!--选择商品-->
    <el-dialog title="选择商品" v-model="dialogTableVisible" size="large">
      <el-row>
        <el-col :span="24">
          <el-form :inline="true" class="demo-form-inline" label-width="80px">
            <el-form-item label="商品名称">
              <el-col :span="18">
                <el-input v-model="formInline.goodName"></el-input>
              </el-col>
            </el-form-item>
            <!--  <el-form-item label="按分类：">
                        <el-select v-model="formInline.classifyCode" style="width: 120px;" @change="selectSort()">
                            <el-option label="全部" value=""></el-option>
                            <el-option :label="item.classifyName" :value="item.classifyName" v-for="item in sortList"></el-option>
                        </el-select>
                        <el-select v-model="formInline.secondCode" style="width: 120px;" v-if="formInline.classifyCode"  @change="selectSort2()">
                            <el-option label="全部" value=""></el-option>
                            <el-option :label="item.classifyName" :value="item.classifyName" v-for="item in secondList"></el-option>
                        </el-select>
                        <el-select v-model="formInline.thcondCode" style="width: 120px;" placeholder="二级分类" v-if="formInline.secondCode">
                            <el-option label="全部" value=""></el-option>
                            <el-option :label="item.classifyName" :value="item.classifyName"
                                   v-for="item in thirdList"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="按状态：">
                        <el-select v-model="formInline.normalState" style="width: 120px;" >
                            <el-option label="全部" value=""></el-option>
                            <el-option label="已启用" value="1" ></el-option>
                            <el-option label="已禁用" value="2" ></el-option>
                        </el-select>
                    </el-form-item> -->
            <el-button type="primary" @click="fetchGoods(1)">查询</el-button>
          </el-form>
        </el-col>
      </el-row>
      <el-table :data="gridData">
        <el-table-column width="215" label="商品">
          <template scope="scope">
            <div style="display: inline-block;">
              <img class="banner" :src="scope.row.goodCover" style="width:55px;">
                    </div>
              <div style="display: inline-block;width: 120px;vertical-align: middle;padding: 10px;">{{scope.row.goodName}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="DIS_PRICE" label="分类">
          <template scope="scope">
            <span>{{ scope.row.goodOneCateName }} - {{ scope.row.goodTwoCateName }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="good_Price" sortable='custom' label="起售价（元）">
          <template scope="scope">
            <span>{{ scope.row.goodPrice }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="T1.good_Discount_Price" label="优惠价（元）">
          <template scope="scope">
            <span v-if="scope.row.goodIsDiscount==1">{{ scope.row.goodDiscountPrice }}</span>
            <span v-else>未启用</span>
          </template>
        </el-table-column>
        <el-table-column prop="good_Ratio" label="补贴比例">
          <template scope="scope">
            <span>{{ scope.row.goodRatio*100 }}%</span>
          </template>
        </el-table-column>
        <el-table-column prop="sales" label="销量">
        </el-table-column>
        <el-table-column prop="stock" label="库存">
        </el-table-column>
        <el-table-column prop="cre_Time" label="上架时间">
          <template scope="scope">
            <span>{{scope.row.creTime}}</span>
          </template>
        </el-table-column>
        <el-table-column label="选择" width="150">
          <template scope="scope">
            <el-checkbox-group v-model="checked" :max="100" @change="handleCheckedCitiesChange">
              <el-checkbox :label="scope.row">选择</el-checkbox>
            </el-checkbox-group>
          </template>
        </el-table-column>
      </el-table>
      <div class="paginate" style="float: left;">
        <el-pagination @current-change="handleCurrentChange" :current-page="pageInfo.pageNum" :page-size="pageInfo.pageSize" layout="total, prev, pager, next, jumper" :total="pageInfo.count">
        </el-pagination>
      </div>
      <div style="float: right;margin-top:19px;margin-right: 20px;">
        <el-checkbox v-model="checkAll" @change="handleCheckAllChange" style="margin-right: 40px;" :indeterminate="isIndeterminate">全选</el-checkbox>
        <el-button type="primary" @click="onSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <!--排序值-->
    <el-dialog title="排序值" v-model="dialogTableVisible2" size="tiny">
      <div style="text-align: center;">
        <el-input v-model="f.sort_value" style="width:150px;"></el-input>
        <div style="margin-top:19px;margin-right: 20px;margin-bottom: 20px;">
          <el-button type="primary" @click="editOrder(f,f.sort_value)">确定</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<style>
</style>
<script>
export default {
  data() {
    return {
      formInline: {
        goodName: '',
        goodOneCate: '',
        goodTwoCate: '',
        goodState: 2,
        storeId: '',
        pageNum: 1,
        pageSize: 5,
        sort: 'T1.CRE_TIME',
        desc: 'DESC',
        goodIsDiscount: ''
      },
      pageInfo: {
        pageNum: 1,
        pageSize: 1,
        count: 1,
        rows: []
      },
      pageInfo2: {
        pageNum: 1,
        pageSize: 5,
        count: 1,
        rows: []
      },
      dialogVisible: false,
      table_loading: false,
      form: {
        goodsCodeList: [],
        operationCode:1
      },
      storeGoodDtos: [],
      dialogTableVisible: false,
      dialogTableVisible2: false,
      gridData: [],
      checked: [],
      checkAll: false,
      isIndeterminate: true,
      arr: [],
      storeGoodDtos: [],
      URL: URL,
      loading: false,
      sortList: [],
      secondList: [],
      thirdList: [],
      f: {},
      flag2: false
    }
  },
  created() {
    this.fetchData();
    // this.fetchGoods(this.pageInfo.pageNum);
    // this.fetchList()
  },
  methods: {
    fetchData() {
      this.dataApi.ajax('operationSelect', { operationCode: 1 }, res => {
        if (res.responseType === 'S') {
          this.pageInfo2 = {
            pageNum: 1,
            pageSize: 5,
            count: 1,
            rows: []
          }
          for (var i = res.dtos.length - 1; i >= 0; i--) {
            res.dtos[i].sort_value = i + 1
            res.dtos[i].index = i
            res.dtos[i].OldProbability = i + 1
          }
          let arr = generateArr(res.dtos)
          this.storeGoodDtos = res.dtos
          this.pageInfo2.count = res.dtos.length
          this.pageInfo2.rows = arr.splice(0, 5)
        }
      });
    },
    fetchGoods(page = 1) {
      this.checked = []
      this.pageInfo.pageNum = page;
      this.formInline.pageNum = page;
      this.dataApi.ajax('selectPageStoreGood', this.formInline, res => {
        if (res.responseType === 'S') {
          this.pageInfo = res
          this.gridData = res.dtos
          this.arr = []
          this.checked = []
          this.inisIndeterminate = true
          for (var i = this.gridData.length - 1; i >= 0; i--) {
            this.arr.push(this.gridData[i])
          }
          if (this.checked.length == this.arr.length) {
            this.checkAll = true
          } else {
            this.checkAll = false;
          }

        }
      });

    },
    fetchList() {
      this.dataApi.ajax('MallGoodClassifyControl/selectOneList', null, res => {
        if (res.responseType === 0) {
          this.sortList = res.goodsClassifyPojos
        }
      });
    },
    selectSort() {
      this.formInline.secondCode = ''
      this.formInline.thcondCode = ''
      this.dataApi.ajax('MallGoodClassifyControl/selectListOne', { classifyName: this.formInline.classifyCode }, res => {
        if (res.responseType === 0) {
          this.secondList = res.goodsClassifyPojos
        }
      });
    },
    selectSort2() {
      if (this.flag2 === true) this.formInline.thcondCode = ''
      this.flag2 = true;
      this.dataApi.ajax('MallGoodClassifyControl/selectListOne', { classifyName: this.formInline.secondCode }, res => {
        //console.log(res)
        if (res.responseType === 0) {
          this.thirdList = res.goodsClassifyPojos
        }
      });
    },
    onSubmit() {

      this.dialogTableVisible = false
      // this.pageInfo2.rows=this.checked
      for (var key in this.storeGoodDtos) {
        for (var i in this.checked) {
          if (this.storeGoodDtos[key].goodId.indexOf(this.checked[i].goodId) !== -1) {
            this.checked.splice([i], 1)
          }
        }
      }

      if (this.checked.length <= 0) {
        return false;
      }
      this.storeGoodDtos = this.storeGoodDtos.concat(this.checked)
      for (var i = this.storeGoodDtos.length - 1; i >= 0; i--) {
        this.storeGoodDtos[i].sort_value = i + 1
        this.storeGoodDtos[i].index = i
        this.storeGoodDtos[i].OldProbability = i + 1
      }
      var arr = generateArr(this.storeGoodDtos)
      this.pageInfo2.count = this.storeGoodDtos.length
      this.pageInfo2.rows = arr.splice(0, 5)

    },
    submit() {   
      let obj = generateObj(this.form)

      if (this.storeGoodDtos.length == 0) {
        this.$message({
          type: 'warning',
          message: '请选择至少一个商品!'
        });
        return;
      }
      var arr = []
      for (var i = 0; i < this.storeGoodDtos.length; i++) {
        arr[i] = this.storeGoodDtos[i].goodId
      }
      obj.goodsCodeList = arr.join(',')

      this.loading = true
    

       this.dataApi.ajax('operationEdit', obj, res => {
          //console.log(res)
          if (res.responseType === 'S') {
            this.showMsg('保存成功')
            this.loading = false;
            this.fetchData();
            
          }
        });


    },
    handleCurrentChange(val) {
      this.fetchGoods(val)
      this.checkAll = false
    },
    handleCurrentChange2(val) {
      this.pageInfo2.pageNum = val
      // console.log(arr.splice(5*(val-1),(5*(val-1)+5)))
      var arr2 = []
      var arr = generateArr(this.storeGoodDtos)
      arr2 = arr.slice(5 * (val - 1), (5 * (val - 1) + 5))
      this.pageInfo2.rows = arr2
    },
    handleCheckAllChange(event) {

      if (event.target.checked == false) {
        for (var i = this.arr.length - 1; i >= 0; i--) {
          for (var j = this.checked.length - 1; j >= 0; j--) {
            if (this.arr.indexOf(this.checked[j]) !== -1) {
              this.checked.splice(j, 1)
            }
          }
        }

      } else {
        this.isIndeterminate = false;
        for (var i = this.gridData.length - 1; i >= 0; i--) {
          if (this.checked.indexOf(this.arr[i]) === -1) {
            this.checked.push(this.arr[i])
          }
        }
      }


    },
    handleCheckedCitiesChange(value) {

      let arr = []
      for (var i = this.arr.length - 1; i >= 0; i--) {
        for (var j = this.checked.length - 1; j >= 0; j--) {
          if (arr.indexOf(this.checked[j]) === -1 && this.arr[i] === this.checked[j]) {
            arr.push(this.checked[j])
          }
        }
      }


      let checkedCount = arr.length;
      this.checkAll = checkedCount === this.arr.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.arr.length;
    },
    deleteRow(index, id) {
      this.pageInfo2.rows.splice(index, 1);
      // this.storeGoodDtos.splice(index, 1);
      for (var i = this.storeGoodDtos.length - 1; i >= 0; i--) {
        if (this.storeGoodDtos[i].goodId.indexOf(id) !== -1) {
          this.storeGoodDtos.splice([i], 1)
        }
      }
      for (var i = this.storeGoodDtos.length - 1; i >= 0; i--) {
        this.storeGoodDtos[i].sort_value = i + 1
        this.storeGoodDtos[i].index = i
        this.storeGoodDtos[i].OldProbability = i + 1
      }
      this.handleCurrentChange2(this.pageInfo2.pageNum)
      this.pageInfo2.count = this.storeGoodDtos.length
    },
    editOrder(item, e) {
      // console.log(item.index)

      // var arr_old=generateArr(this.storeGoodDtos)
      // this.storeGoodDtos=[]
      // this.storeGoodDtos=arr_old 
      // this.pageInfo2.rows=[]
      var val = e //输入的排序值
      if (!isFloat(e)) {
        this.showMsg('输入的排序值不正确', 'warning')
        return
      }
      // console.log(e.target.value,item.OldProbability)
      // return;
      if (Math.floor(val) <= 0) {
        val = item.OldProbability || 0;
        return false;
      }
      if (item.OldProbability == val) return false;
      if (val > this.storeGoodDtos.length) {
        this.showMsg('排序值不能大于总数', 'warning')
        item.sort_value = item.OldProbability
        return false;
      }
      //let currentList = this.pageInfo2.rows;

      let newVal = this.storeGoodDtos[item.index] //获取当前的元素值


      let oldVal = this.storeGoodDtos[val - 1] //获取要替换的元素值



      this.storeGoodDtos.splice(val - 1, 1, newVal) //替换旧值并新增的新值
      this.storeGoodDtos.splice(item.index, 1, oldVal) //替换新值并新增的旧值
      // console.log(this.storeGoodDtos,item.OldProbability-1,index-1)
      // console.log(item.OldProbability,val)//旧的排序值

      oldVal.index = item.index
      newVal.index = parseInt(val - 1)

      // oldVal.sort_value = oldVal.index+1+""
      // newVal.sort_value = newVal.index+1+""

      for (var i = this.storeGoodDtos.length - 1; i >= 0; i--) {

        // this.$set(this.storeGoodDtos[i],'sort_value',this.storeGoodDtos[i].index+1+"")
        this.storeGoodDtos[i].sort_value = this.storeGoodDtos[i].index + 1 + ""

        //console.log(this.storeGoodDtos[i].sort_value);
      }

      this.handleCurrentChange2(this.pageInfo2.pageNum) //根据所有数据数组切割成当前页数组
      this.dialogTableVisible2 = false
    },
    setOldProbability(item, index) {
      item.OldProbability = index
    },
    fanhui() {
      history.back(-1)
    },
    uploading(f) {
      this.dataApi.upload('file/upload', f.file, res => {
        //console.log(res)
        if (res.responseType === 0) {
          f.images.splice(f.index, 1, this.URL + res.fileName)
        }
      });
    },
    showDilog(item) {
      this.dialogTableVisible2 = true
      this.f = item
    }
  }
}

</script>
